
package com.ami.iusb;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import javax.swing.JOptionPane;

import com.ami.iusb.protocol.FloppyProtocol;
import com.ami.iusb.protocol.IUSBSCSI;
import com.ami.iusb.protocol.PacketMaster;
import com.ami.kvm.imageredir.IUSBHeader;
import com.ami.kvm.jviewer.Debug;
import com.ami.kvm.jviewer.JViewer;
import com.ami.kvm.jviewer.gui.InfoDialog;
import com.ami.kvm.jviewer.gui.JViewerApp;
import com.ami.kvm.jviewer.gui.LocaleStrings;
import com.ami.kvm.jviewer.gui.StandAloneConnectionDialog;
import com.ami.vmedia.VMApp;

public class FloppyRedir extends Thread {
	private PacketMaster packetMaster;
	private FloppyProtocol protocol;
	private ByteBuffer packetReadBuffer;
	private ByteBuffer packetWriteBuffer;
	private boolean physicalDevice;
	private int FDDevice_no;
	private boolean running = false;
	private boolean stopRunning = false;
	private long nativeReaderPointer = -1L;
	private Thread redirThread;
	private String sourceFloppy = null;
	private int nBytesRedirected = 0;
	private int fdInstanceNum;
	private boolean fdReconnect = false;
	private static final int DEVICE_REDIRECTION_ACK = 241;
	private static final int AUTH_CMD = 242;
	private static final int MAX_READ_SECTORS = 256;
	private static final int MAX_READ_SIZE = 131072;
	public static final int READ_WRITE = 1;
	public static final int READ_ONLY = 2;
	public static final int SECTOR_RANGE_ERROR = -1;
	public static final int ALREADY_IN_USE = -3;
	public static final int MEDIA_ERROR = -4;
	private boolean fdImageRedirected = false;
	private boolean fdImageEjected = false;
	private boolean fdServiceRestarted = false;
	private vFlpyMonitorThread vMThread = null;
	private String errorMessage = " ";

	private static Object syncObj = new Object();
	private boolean confModified = false;
	private boolean fdRedirectionKilled = false;
	private boolean fdStoppedByUser = false;

	private int floppyRedirStatus;
	private int floppyDeviceStatus;
	private int fdStopMode;

//	static {
//		try {
//			if ((!JViewer.isdownloadapp()) && (!JViewer.isplayerapp())) {
//				if (JViewer.isjviewerapp()) {
//					System.loadLibrary("javafloppywrapper");
//				} else {
//					loadWrapperLibrary();
//				}
//			}
//		} catch (UnsatisfiedLinkError localUnsatisfiedLinkError) {
//			System.err.println(LocaleStrings.getString("5_2_FLOPPYREDIR"));
//		}
//	}
	
	static {
		String path = System.getProperty("user.dir") + File.separator + "native" + File.separator
				+ "javafloppywrapper.dll";
		System.load(path);
	}

	private static void loadWrapperLibrary() {
		String str1 = null;

		String str2 = JViewer.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		str2 = str2.substring(0, str2.lastIndexOf('/'));

		if (str2.contains("%20")) {
			str2 = str2.replaceAll("%20", "\\ ");
		}

		String str3 = File.separator + "Jar" + File.separator + JViewer.getIp() + File.separator + "lib"
				+ File.separator;

		File localFile = null;

		if (System.getProperty("os.name").startsWith("Windows")) {
			if ((JViewer.isStandAloneApp()) || (JViewer.isVMApp())) {
				str3 = StandAloneConnectionDialog.replaceAllPattern(str3, ":", "_");
				str1 = str2 + str3 + "javafloppywrapper.dll";
				localFile = new File(str1);
				if (false == StandAloneConnectionDialog.getWrapperLibrary("javafloppywrapper.dll")) {
					Debug.out.println("Unable to extract the javafloppywrapper.dll");
					str1 = null;
				}
			} else {
				str1 = System.getProperty("user.dir") + str3 + "javafloppywrapper.dll";
			}
		} else if (System.getProperty("os.name").startsWith("Linux")) {
			if ((JViewer.isStandAloneApp()) || (JViewer.isVMApp())) {
				str1 = str2 + str3 + "libjavafloppywrapper.so";
				localFile = new File(str1);
				if (false == StandAloneConnectionDialog.getWrapperLibrary("libjavafloppywrapper.so")) {
					Debug.out.println("Unable to extract the libjavafloppywrapper.so");
					str1 = null;
				}
			} else {
				str1 = System.getProperty("user.dir") + str3 + "libjavafloppywrapper.so";
			}
		} else if (System.getProperty("os.name").startsWith("Mac"))
			if ((JViewer.isStandAloneApp()) || (JViewer.isVMApp())) {
				str1 = str2 + str3 + "libjavafloppywrapper.jnilib";
				localFile = new File(str1);
				if (false == StandAloneConnectionDialog.getWrapperLibrary("libjavafloppywrapper.jnilib")) {
					Debug.out.println("Unable to extract the libjavafloppywrapper.jnilib");
					str1 = null;
				}
			} else {
				str1 = System.getProperty("user.dir") + str3 + "libjavafloppywrapper.jnilib";
			}
		try {
			System.load(str1);
		} catch (UnsatisfiedLinkError localUnsatisfiedLinkError) {
			Debug.out.println(localUnsatisfiedLinkError);
			showLibraryLoadError();
		} catch (Exception localException) {
			Debug.out.println(localException);
			showLibraryLoadError();
		}
	}

	public FloppyRedir(boolean paramBoolean) {
		this.physicalDevice = paramBoolean;
		this.floppyRedirStatus = 0;
		this.floppyDeviceStatus = 1;
		this.fdStopMode = 0;
		this.protocol = new FloppyProtocol();
		this.packetReadBuffer = ByteBuffer.allocateDirect(131134);

		this.packetWriteBuffer = ByteBuffer.allocateDirect(131134);
	}

	private int floppyConnect(String paramString, int paramInt, boolean paramBoolean) throws IOException {
		this.packetMaster = new PacketMaster(paramString, paramInt, false, this.protocol, paramBoolean);
		this.packetMaster.setupBuffers(this.packetReadBuffer, this.packetWriteBuffer);
		this.packetMaster.setBufferEndianness(ByteOrder.LITTLE_ENDIAN, ByteOrder.LITTLE_ENDIAN);
		if (JViewer.isSinglePortEnabled()) {
			if (JViewerApp.getInstance().getSinglePortKvm().setHTTPConnect("FDMEDIA") < 0) {
				setErrorMessage(LocaleStrings.getString("5_3_FLOPPYREDIR") + paramInt
						+ LocaleStrings.getString("5_4_FLOPPYREDIR"));
				return -1;
			}
			this.packetMaster.setSock(JViewerApp.getInstance().getSinglePortKvm().getHttpsock());

		} else if (this.packetMaster.connectVmedia(paramBoolean) < 0) {
			setErrorMessage(
					LocaleStrings.getString("5_3_FLOPPYREDIR") + paramInt + LocaleStrings.getString("5_4_FLOPPYREDIR"));
			return -1;
		}

		return 0;
	}

	private void floppyDisconnect() {
		try {
			this.packetMaster.VmediaSockclose();
		} catch (IOException localIOException) {
			System.err.println(LocaleStrings.getString("5_5_FLOPPYREDIR") + localIOException.getMessage());
		}
	}

	public boolean startRedirection(String paramString1, String paramString2, int paramInt1, String paramString3,
			int paramInt2, boolean paramBoolean) throws RedirectionException {
		if (this.running)
			return true;
		this.FDDevice_no = paramInt1;
		IUSBRedirSession localIUSBRedirSession = null;

		localIUSBRedirSession = VMApp.getInstance().getIUSBRedirSession();
		try {
			if (floppyConnect(paramString1, paramInt2, paramBoolean) < 0) {
				return false;
			}
			SendAuth_SessionToken(paramString3);

			IUSBSCSI localIUSBSCSI = recvRequest();
			this.fdInstanceNum = localIUSBSCSI.instanceNum;
			if (localIUSBSCSI.opcode == 241) {
				if (localIUSBSCSI.connectionStatus == 5) {
					floppyDisconnect();
					setErrorMessage(LocaleStrings.getString("4_17_CDROMREDIR"));
					return false;
				}
				if (localIUSBSCSI.connectionStatus == 8) {
					floppyDisconnect();
					setErrorMessage(LocaleStrings.getString("5_10_FLOPPYREDIR"));
					return false;
				}
				if (localIUSBSCSI.connectionStatus == 13) {
					floppyDisconnect();
					setErrorMessage(LocaleStrings.getString("F_136_JVM"));
					return false;
				}
				if (localIUSBSCSI.connectionStatus != 1) {
					floppyDisconnect();

					if (localIUSBSCSI.m_otherIP != null) {
						if ((localIUSBSCSI.m_otherIP.equalsIgnoreCase("127.0.0.1"))
								|| (localIUSBSCSI.m_otherIP.equalsIgnoreCase("::1"))) {
							setErrorMessage(LocaleStrings.getString("4_19_CDROMREDIR"));
						} else
							setErrorMessage(LocaleStrings.getString("4_7_CDROMREDIR") + localIUSBSCSI.m_otherIP);
					}
					return false;
				}
			} else {
				floppyDisconnect();
				throw new RedirectionException(LocaleStrings.getString("4_8_CDROMREDIR") + localIUSBSCSI.opcode);
			}
		} catch (IOException localIOException) {
			throw new RedirectionException(localIOException.getMessage());
		}

		if (this.nativeReaderPointer == -1L)
			newFloppyReader(this.physicalDevice);
		this.sourceFloppy = paramString2;
		try {
			int i = openFloppy(paramString2.getBytes("UTF-8"));
			if (i == 2) {

				InfoDialog.showDialog(VMApp.getVMFrame(), LocaleStrings.getString("4_13_CDROMREDIR"),
						LocaleStrings.getString("A_6_GLOBAL"), 1);

			} else {

				if (i == -3) {
					if (localIUSBRedirSession.isFloppyPhysicalDrive(this.FDDevice_no)) {
						setErrorMessage(LocaleStrings.getString("6_37_IUSBREDIR"));
					} else {
						setErrorMessage(LocaleStrings.getString("5_8_FLOPPYREDIR"));
					}
				} else if ((i == -4) || (i == -1)) {
					setErrorMessage(LocaleStrings.getString("5_12_FLOPPYREDIR"));
				}
				System.err.println(LocaleStrings.getString("5_6_FLOPPYREDIR"));
				deleteFloppyReader();
				floppyDisconnect();
				return false;
			}
		} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
			System.out.println(LocaleStrings.getString("4_12_CDROMREDIR"));
		}
		if (!JViewer.isVMApp())
			JViewerApp.getInstance().getKVMClient().MediaRedirectionState((byte) 1);
		this.nBytesRedirected = 0;

		this.redirThread = new Thread(this);
		this.redirThread.start();
		this.floppyRedirStatus = 1;
		if (localIUSBRedirSession.isFloppyPhysicalDrive(this.FDDevice_no)) {
			this.vMThread = new vFlpyMonitorThread(this.FDDevice_no);
			this.vMThread.startFloppyMonitor();
		}
		this.running = true;
		return true;
	}

	public boolean stopRedirection() {
		if (this.running) {
			try {
				if (!isFdServiceRestarted()) {
					IUSBSCSI.sendCommandToMediaServer(this.packetMaster, this.packetWriteBuffer, null, 247);
				}
			} catch (Exception localException) {
				Debug.out
						.println("Sending MEDIA_SESSION_DISCONNECT command to media server failed : " + localException);
			}

			this.stopRunning = true;
			floppyDisconnect();
			try {
				this.redirThread.join();
			} catch (InterruptedException localInterruptedException) {
				System.err.println(LocaleStrings.getString("5_7_FLOPPYREDIR"));
			}
			if (!JViewer.isVMApp())
				JViewerApp.getInstance().getKVMClient().MediaRedirectionState((byte) 0);
			this.running = false;
			this.stopRunning = false;
			closeFloppy();
			deleteFloppyReader();
		}
		this.nBytesRedirected = 0;
		this.floppyRedirStatus = 0;
		return true;
	}

	private IUSBSCSI recvRequest() throws IOException, RedirectionException {
		return (IUSBSCSI) this.packetMaster.receivePacket();
	}

	public boolean isRedirActive() {
		return this.running;
	}

	public String getSourceDrive() {
		return this.sourceFloppy;
	}

	public void stopRedirectionAbnormal() {
		if (this.running) {
			this.stopRunning = true;
			floppyDisconnect();
			this.running = false;
			this.stopRunning = false;
			closeFloppy();
			deleteFloppyReader();
			JViewerApp.getInstance().reportFloppyAbnormal(this.FDDevice_no);
		}
		this.floppyRedirStatus = 0;
	}

	public void run() {
		int i = 0;

		while (!this.stopRunning) {
			try {
				this.packetWriteBuffer.rewind();

				IUSBSCSI localIUSBSCSI1 = recvRequest();
				if (localIUSBSCSI1 != null) {

					int j = executeFloppySCSICmd(this.packetReadBuffer, this.packetWriteBuffer);
					this.packetWriteBuffer.limit(j);
					if (localIUSBSCSI1.opcode == 246) {

						this.fdRedirectionKilled = true;
						return;
					}
					if (localIUSBSCSI1.opcode == 247) {
						this.fdServiceRestarted = true;
						return;
					}

					IUSBSCSI localIUSBSCSI2 = new IUSBSCSI(this.packetWriteBuffer, true);

					this.packetMaster.sendPacket(localIUSBSCSI2);
					i += j;
					this.nBytesRedirected += i / 1024;
					i %= 1024;

					if (localIUSBSCSI1.opcode == 27) {
						if (localIUSBSCSI1.Lba == 2)
							this.fdImageEjected = true;
					}
				}
			} catch (Exception localException) {
				Debug.out.println(localException);
				if (!this.stopRunning) {
					if ((JViewer.isKVMReconnectEnabled())
							&& (JViewerApp.getInstance().GetRedirectionState() != JViewerApp.REDIR_STOPPING)
							&& (JViewerApp.getInstance().GetRedirectionState() != JViewerApp.REDIR_STOPPED)) {

						if (JViewerApp.getInstance().getRetryConnection()) {

							Debug.out.println(
									"\n Floppy redierction thread returned .because of KVM Reconnect in progress\n");
							return;
						}
					}

					synchronized (getSyncObj()) {
						try {
							if (!this.confModified) {
								if (JViewer.isVMApp()) {
									getSyncObj().wait(1000L);
								} else
									getSyncObj().wait(10000L);
								if (this.fdStoppedByUser == true) {

									return;
								}
							}
						} catch (InterruptedException localInterruptedException) {
							localInterruptedException.printStackTrace();
						}
					}
					if (!this.confModified) {
						handleError(LocaleStrings.getString("5_1_FLOPPYREDIR"));
					} else
						this.confModified = false;
					stopRedirectionAbnormal();
					return;
				}
			}
		}
	}

	public String[] getFloppyList() {
		if (!this.physicalDevice) {
			DisplayErrorMsg("Cannot get Floppy drive list during Floppy IMAGE redirection");
			return null;
		}

		if (this.nativeReaderPointer == -1L) {
			newFloppyReader(true);
		}
		String[] arrayOfString1 = null;
		arrayOfString1 = listFloppyDrives();
		String[] arrayOfString2 = null;

		if (arrayOfString1 != null) {
			int i = 0;
			for (int j = 0; j < arrayOfString1.length; j++) {
				if ((j <= 0) || (!arrayOfString1[j].equals(arrayOfString1[(j - 1)]))) {
					arrayOfString1[(i++)] = arrayOfString1[j];
				}
			}
			arrayOfString2 = new String[i];
			System.arraycopy(arrayOfString1, 0, arrayOfString2, 0, i);
		}
		return arrayOfString2;
	}

	public String getLIBFLOPPYVersion() {
		String str;

		if (this.nativeReaderPointer == -1L) {
			newFloppyReader(false);
			str = getVersion();
			deleteFloppyReader();
		} else {
			str = getVersion();
		}
		return str;
	}

	public void DisplayErrorMsg(String paramString) {
		if (JViewer.isVMApp()) {
			VMApp.getInstance().generalErrorMessage(LocaleStrings.getString("4_16_CDROMREDIR"), paramString);
		} else {
			JViewerApp.getInstance().getMainWindow().generalErrorMessage(LocaleStrings.getString("4_16_CDROMREDIR"),
					paramString);
		}
	}

	public void handleError(String paramString) {
		DisplayErrorMsg(paramString);
	}

	public boolean isPhysicalDevice() {
		return this.physicalDevice;
	}

	public void SendAuth_SessionToken(String paramString) throws RedirectionException, IOException {
		int i = 0;
		int j = JViewerApp.getInstance().getSessionTokenType();

		if (j == 0) {
			i = 128;
			this.packetWriteBuffer.clear();
			this.packetWriteBuffer.limit(160);
		} else if (j == 1) {
			i = 240;
			this.packetWriteBuffer.clear();
			this.packetWriteBuffer.limit(272);
		}

		IUSBHeader localIUSBHeader = new IUSBHeader(i);
		localIUSBHeader.write(this.packetWriteBuffer);
		this.packetWriteBuffer.position(41);
		this.packetWriteBuffer.put((byte) -14);
		this.packetWriteBuffer.position(62);
		this.packetWriteBuffer.put((byte) 0);
		this.packetWriteBuffer.put(paramString.getBytes());
		this.packetWriteBuffer.position(23);
		this.packetWriteBuffer.put((byte) this.FDDevice_no);
		this.packetWriteBuffer.position(0);
		IUSBSCSI localIUSBSCSI = new IUSBSCSI(this.packetWriteBuffer, true);
		this.packetMaster.sendPacket(localIUSBSCSI);
	}

	public byte ReadKeybdLEDStatus() {
		byte b = 0;
		try {
			// TODO tianlin
			 b = GetLEDStatus();
		} catch (UnsatisfiedLinkError localUnsatisfiedLinkError) {
			Debug.out.println("UnsatisfiedLinkError");
			Debug.out.println(localUnsatisfiedLinkError);
		} catch (Exception localException) {
			Debug.out.println(localException);
		}
		return b;
	}

	public void setKeyboardLEDStatus(byte paramByte) {
		try {
			SetLEDStatus(paramByte);
		} catch (UnsatisfiedLinkError localUnsatisfiedLinkError) {
			Debug.out.println("UnsatisfiedLinkError");
			Debug.out.println(localUnsatisfiedLinkError);
		} catch (Exception localException) {
			Debug.out.println(localException);
		}
	}

	public int getBytesRedirected() {
		return this.nBytesRedirected;
	}

	public static Object getSyncObj() {
		return syncObj;
	}

	public boolean isConfModified() {
		return this.confModified;
	}

	public void setConfModified(boolean paramBoolean) {
		this.confModified = paramBoolean;
	}

	public String ReadKeybdType() {
		String str = null;
		try {
			str = GetKeyboardName();
		} catch (UnsatisfiedLinkError localUnsatisfiedLinkError) {
			Debug.out.println("UnsatisfiedLinkError");
			Debug.out.println(localUnsatisfiedLinkError);
		} catch (Exception localException) {
			Debug.out.println(localException);
		}
		return str;
	}

	public int getFdInstanceNum() {
		return this.fdInstanceNum;
	}

	public boolean isFdImageRedirected() {
		return this.fdImageRedirected;
	}

	public void setFdImageRedirected(boolean paramBoolean) {
		this.fdImageRedirected = paramBoolean;
	}

	public boolean isFdImageEjected() {
		return this.fdImageEjected;
	}

	public boolean isFdRedirectionKilled() {
		return this.fdRedirectionKilled;
	}

	public void setFdReconnect(boolean paramBoolean) {
		this.fdReconnect = paramBoolean;
	}

	public boolean getFdReconnect() {
		return this.fdReconnect;
	}

	public boolean isFdStoppedByUser() {
		return this.fdStoppedByUser;
	}

	public void setFdStoppedByUser(boolean paramBoolean) {
		this.fdStoppedByUser = paramBoolean;
	}

	public String getErrorMessage() {
		return this.errorMessage;
	}

	public void setErrorMessage(String paramString) {
		this.errorMessage = paramString;
	}

	public void setFdRedirectionKilled(boolean paramBoolean) {
		this.fdRedirectionKilled = paramBoolean;
	}

	public int getFloppyRedirStatus() {
		return this.floppyRedirStatus;
	}

	public void setFloppyRedirStatus(int paramInt) {
		this.floppyRedirStatus = paramInt;
	}

	public int getFloppyDeviceStatus() {
		return this.floppyDeviceStatus;
	}

	public void setFloppyDeviceStatus(int paramInt) {
		this.floppyDeviceStatus = paramInt;
	}

	public int getFdStopMode() {
		return this.fdStopMode;
	}

	public void setFdStopMode(int paramInt) {
		this.fdStopMode = paramInt;
	}

	public boolean isFdServiceRestarted() {
		return this.fdServiceRestarted;
	}

	private static void showLibraryLoadError() {
		if (JViewer.isVMApp()) {
			JOptionPane.showMessageDialog(VMApp.getVMFrame(), LocaleStrings.getString("5_13_FLOPPYREDIR"),
					LocaleStrings.getString("1_3_JVIEWER"), 0);

			VMApp.exit(0);
		} else {
			JOptionPane.showMessageDialog(JViewer.getMainFrame(), LocaleStrings.getString("5_13_FLOPPYREDIR"),
					LocaleStrings.getString("1_3_JVIEWER"), 0);

			JViewerApp.getInstance().getM_frame().windowClosed();
		}
	}

	private native String[] listFloppyDrives();

	private native void newFloppyReader(boolean paramBoolean);

	private native void deleteFloppyReader();

	private native int openFloppy(byte[] paramArrayOfByte);

	private native void closeFloppy();

	private native int executeFloppySCSICmd(ByteBuffer paramByteBuffer1, ByteBuffer paramByteBuffer2);

	private native String GetKeyboardName();

	private native byte GetLEDStatus();

	private native byte SetLEDStatus(byte paramByte);

	private native String getVersion();
}

/*
 * Location:
 * D:\Users\tianlin\Downloads\JViewer.jar!\com\ami\iusb\FloppyRedir.class Java
 * compiler version: 5 (49.0) JD-Core Version: 0.7.1
 */